//
//  PlSAppSpecifier.m
//  Injector
//
//  Created by ∞ on 13/11/07.
//  Copyright 2007 Emanuele Vulcano. All rights reserved.
//

#import "PlSAppSpecifier.h"

const double kPlSAnyVersion = -1.0;

@implementation PlSAppSpecifier

@synthesize bundleIdentifier, minVersion, maxVersion;

- (id) initWithBundleIdentifier:(NSString*) ident
					 minVersion:(double) minV
					 maxVersion:(double) maxV {
	if (self = [super init]) {
		bundleIdentifier = [ident copy];
		minVersion = minV;
		maxVersion = maxV;
	}
	
	return self;
}

+ (id) specifierWithBundleIdentifier:(NSString*) ident
						  minVersion:(double) minV
						  maxVersion:(double) maxV {
	return [[[self alloc] initWithBundleIdentifier:ident minVersion:minV maxVersion:maxV] autorelease];
}

- (void) dealloc {
	[bundleIdentifier release];
	[super dealloc];
}

+ (id) anyApplication {
	static id myself = nil;
	if (!myself) myself = [[self alloc] initWithBundleIdentifier:@"*" minVersion:kPlSAnyVersion maxVersion:kPlSAnyVersion];
	
	return myself;
}

- (BOOL) isCompatibleWithApplication:(NSBundle*) app {
	if (self == [PlSAppSpecifier anyApplication]) return YES;
	
	NSDictionary* info = [app infoDictionary];
	NSString* b = [info objectForKey:@"CFBundleIdentifier"];
	if (![b isEqual:self.bundleIdentifier])
		return NO;
	
	if (minVersion == kPlSAnyVersion || maxVersion == kPlSAnyVersion)
		return YES;
	
	id versionObj = [info objectForKey:@"CFBundleVersion"];
	double version = kPlSAnyVersion;
	if (versionObj)
		version = [versionObj doubleValue];
	if (version < 0)
		version = kPlSAnyVersion;
	if (version == kPlSAnyVersion)
		return YES;
	
	return (minVersion == kPlSAnyVersion || minVersion <= version) &&
		(maxVersion == kPlSAnyVersion || maxVersion >= version);
}

+ (BOOL) anySpecifier:(NSArray*) specs isCompatibleWithApplication:(NSBundle*) app {
	L0Log(@"%@", specs);
	for (PlSAppSpecifier* spec in specs) {
		if ([spec isCompatibleWithApplication:app]) return YES;
	}
	
	return NO;
}

- (NSString*) description {
	if (self == [PlSAppSpecifier anyApplication])
		return [NSString stringWithFormat:@"%@ { any application }", [super description]];
	else
		return [NSString stringWithFormat:@"%@ { bundle identifier = %@, minimum version = %@, maximum version = %@ }",
				[super description],
				self.bundleIdentifier,
				(self.minVersion == kPlSAnyVersion)? @"any" : [NSNumber numberWithDouble:self.minVersion],
				(self.maxVersion == kPlSAnyVersion)? @"any" : [NSNumber numberWithDouble:self.maxVersion]];
}
				

@end
